<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI对话 - UFO Max</title>
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            display: flex;
            height: 100vh;
            overflow: hidden;
            background-color: #1e1e1e;
            color: #d4d4d4;
        }

        /* 主容器 */
        .chat-container {
            display: flex;
            flex-direction: column;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        /* 顶部导航栏 */
        .chat-header {
            padding: 15px;
            background-color: #252526;
            border-bottom: 1px solid #3e3e42;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .chat-title {
            font-size: 18px;
            font-weight: bold;
            display: flex;
            align-items: center;
        }

        .chat-title span {
            margin-right: 8px;
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-button {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #464647;
            transition: background-color 0.2s;
        }

        .status-button:hover {
            background-color: #5a5a5c;
        }

        .status-button.status-connected {
            background-color: #4ec9b0;
            color: #1e1e1e;
        }

        .status-button.status-disconnected {
            background-color: #f44747;
            color: white;
        }

        .settings-button {
            background-color: #464647;
            color: #cccccc;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .settings-button:hover {
            background-color: #5a5a5c;
        }

        /* 设置弹窗样式 */
        .settings-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }

        .settings-content {
            background-color: #252526;
            border-radius: 8px;
            padding: 20px;
            width: 90%;
            max-width: 500px;
            border: 1px solid #3e3e42;
        }

        .settings-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .settings-title {
            font-size: 18px;
            font-weight: bold;
        }

        .close-button {
            background: none;
            border: none;
            color: #cccccc;
            font-size: 20px;
            cursor: pointer;
        }

        .close-button:hover {
            color: #d4d4d4;
        }

        .settings-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .setting-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .setting-label {
            font-size: 12px;
            color: #cccccc;
        }

        .setting-input {
            padding: 8px 12px;
            background-color: #ffffff;
            border: 1px solid #3e3e42;
            border-radius: 4px;
            color: #3c3c3c;
            font-size: 14px;
        }

        .setting-input:focus {
            outline: none;
            border-color: #0e639c;
        }

        .setting-select {
            padding: 8px 12px;
            background-color: #fffff;
            border: 1px solid #3e3e42;
            border-radius: 4px;
            color: #3e3e42;
            font-size: 14px;
            cursor: pointer;
        }

        .setting-select:focus {
            outline: none;
            border-color: #0e639c;
        }

        .settings-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .cancel-button {
            padding: 8px 16px;
            background-color: #464647;
            color: #cccccc;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .cancel-button:hover {
            background-color: #5a5a5c;
        }

        .save-button {
            padding: 8px 16px;
            background-color: #0e639c;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .save-button:hover {
            background-color: #1177bb;
        }

        /* 聊天内容区域 */
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* 消息样式 */
        .message {
            padding: 12px 16px;
            border-radius: 8px;
            max-width: 80%;
            word-wrap: break-word;
            position: relative;
        }

        .message.user {
            align-self: flex-end;
            background-color: #0e639c;
            color: white;
        }

        .message.ai {
            align-self: flex-start;
            background-color: #2d2d30;
            border: 1px solid #3e3e42;
        }

        .message.system {
            align-self: center;
            background-color: #464647;
            color: #cccccc;
            font-size: 12px;
            max-width: 60%;
            text-align: center;
        }

        .message-timestamp {
            font-size: 10px;
            opacity: 0.6;
            margin-top: 4px;
            text-align: right;
        }

        .message.ai .message-timestamp {
            text-align: left;
        }

        .loading-indicator {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #cccccc;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 0.8s linear infinite;
            margin-right: 8px;
            vertical-align: middle;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 输入区域 */
        .chat-input-area {
            padding: 15px;
            background-color: #252526;
            border-top: 1px solid #3e3e42;
        }

        .config-section {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
            align-items: center;
        }

        .config-group {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .config-group label {
            font-size: 12px;
            color: #cccccc;
        }

        .config-input {
            padding: 6px 10px;
            background-color: #3c3c3c;
            border: 1px solid #3e3e42;
            border-radius: 4px;
            color: #d4d4d4;
            font-size: 12px;
            width: 200px;
        }

        .config-input:focus {
            outline: none;
            border-color: #0e639c;
        }

        .input-wrapper {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            padding: 10px;
            background-color: #3c3c3c;
            border: 1px solid #3e3e42;
            border-radius: 4px;
            color: #d4d4d4;
            font-family: inherit;
            font-size: 14px;
            resize: none;
            min-height: 60px;
            max-height: 150px;
        }

        .message-input:focus {
            outline: none;
            border-color: #0e639c;
        }

        .message-input:disabled {
            background-color: #2d2d30;
            color: #666666;
            cursor: not-allowed;
        }

        .send-button {
            padding: 10px 20px;
            background-color: #0e639c;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            white-space: nowrap;
        }

        .send-button:hover:not(:disabled) {
            background-color: #1177bb;
        }

        .send-button:disabled {
            background-color: #464647;
            color: #666666;
            cursor: not-allowed;
        }

        /* 滚动条样式 */
        .chat-messages::-webkit-scrollbar {
            width: 8px;
        }

        .chat-messages::-webkit-scrollbar-track {
            background-color: #2d2d30;
        }

        .chat-messages::-webkit-scrollbar-thumb {
            background-color: #464647;
            border-radius: 4px;
        }

        .chat-messages::-webkit-scrollbar-thumb:hover {
            background-color: #666666;
        }
    </style>
</head>
<body>
    <!-- 聊天容器 -->
    <div class="chat-container">
        <!-- 顶部导航栏 -->
        <div class="chat-header">
            <div class="chat-title">
                <span>🤖</span> AI对话助手
            </div>
            <div class="header-actions">
                <button id="status-button" class="status-button status-disconnected" title="未连接，点击连接">
                    <span id="status-icon">⚠</span>
                </button>
                <button id="settings-button" class="settings-button">设置</button>
            </div>
        </div>

        <!-- 设置弹窗 -->
        <div id="settings-modal" class="settings-modal">
            <div class="settings-content">
                <div class="settings-header">
                    <h3 class="settings-title">AI设置</h3>
                    <button id="close-settings" class="close-button">×</button>
                </div>
                <form id="settings-form" class="settings-form">
                    <div class="setting-group">
                        <label for="setting-model-id" class="setting-label">模型ID</label>
                        <input type="text" id="setting-model-id" class="setting-input" placeholder="输入模型ID">
                    </div>
                    <div class="setting-group">
                        <label for="setting-api-key" class="setting-label">API密钥</label>
                        <input type="text" id="setting-api-key" class="setting-input" placeholder="输入API密钥">
                    </div>
                    <div class="setting-group">
                        <label for="setting-max-tokens" class="setting-label">最大Token数</label>
                        <input type="number" id="setting-max-tokens" class="setting-input" placeholder="最大生成Token数" min="1" max="10000">
                    </div>
                    <div class="setting-group">
                        <label for="setting-temperature" class="setting-label">温度值</label>
                        <input type="number" id="setting-temperature" class="setting-input" placeholder="生成多样性" min="0" max="2" step="0.1">
                    </div>
                    <div class="setting-group">
                        <label for="setting-max-context" class="setting-label">最大上下文长度</label>
                        <input type="number" id="setting-max-context" class="setting-input" placeholder="上下文消息数" min="1" max="100">
                    </div>
                    <div class="setting-group">
                        <label for="setting-thinking" class="setting-label">思考模式</label>
                        <select id="setting-thinking" class="setting-select">
                            <option value="disabled">禁用</option>
                            <option value="enabled">启用</option>
                            <option value="auto">自动</option>
                        </select>
                    </div>
                    <div class="setting-group">
                        <label for="setting-rule-file" class="setting-label">规则文件路径</label>
                        <input type="text" id="setting-rule-file" class="setting-input" placeholder="规则文件路径，如/fs/rule/rule.txt">
                    </div>
                    <div class="settings-actions">
                        <button type="button" id="cancel-settings" class="cancel-button">取消</button>
                        <button type="submit" class="save-button">保存</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 聊天内容区域 -->
        <div class="chat-messages" id="chat-messages">
            <div class="message system">
                <span>欢迎使用AI对话助手，请连接RPC服务器开始聊天</span>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-area">
            <div class="input-wrapper">
                <textarea id="message-input" class="message-input" placeholder="输入您的问题..." disabled></textarea>
                <button id="send-button" class="send-button" disabled>发送</button>
            </div>
        </div>
    </div>

    <!-- 导入必要的JavaScript文件 -->
    <script src="../javascript/rpc.js"></script>
    <script src="../javascript/volcano_api.js"></script>
    
    <script>
        // 全局变量
        let rpcClient = null;
        let luaRpc = null;
        let volcanoApiRpc = null;
        let volcanoApi = null;
        let isConnected = false;
        let isApiInitialized = false;

        // DOM元素
        const chatMessages = document.getElementById('chat-messages');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const statusButton = document.getElementById('status-button');
        const statusIcon = document.getElementById('status-icon');
        const settingsButton = document.getElementById('settings-button');
        const settingsModal = document.getElementById('settings-modal');
        const closeSettings = document.getElementById('close-settings');
        const cancelSettings = document.getElementById('cancel-settings');
        const settingsForm = document.getElementById('settings-form');
        const settingModelId = document.getElementById('setting-model-id');
        const settingApiKey = document.getElementById('setting-api-key');
        const settingMaxTokens = document.getElementById('setting-max-tokens');
        const settingTemperature = document.getElementById('setting-temperature');
        const settingMaxContext = document.getElementById('setting-max-context');
        const settingThinking = document.getElementById('setting-thinking');
        const settingRuleFile = document.getElementById('setting-rule-file');

        // 加载保存的设置
        let aiSettings = {
            modelId: 'doubao-seed-1-6-flash-250828',
            apiKey: '403fbb1e-d61c-4183-b71c-075635b39879',
            maxTokens: 2000,
            temperature: 0.7,
            maxContextLength: 20,
            thinking: 'disabled',
            ruleFilePath: '/fs/rule/rule.txt'
        };

        // 从localStorage加载设置
        function loadSettings() {
            const savedSettings = localStorage.getItem('aiSettings');
            if (savedSettings) {
                try {
                    aiSettings = {...aiSettings, ...JSON.parse(savedSettings)};
                    // 更新设置表单的值
                    settingModelId.value = aiSettings.modelId;
                    settingApiKey.value = aiSettings.apiKey;
                    settingMaxTokens.value = aiSettings.maxTokens;
                    settingTemperature.value = aiSettings.temperature;
                    settingMaxContext.value = aiSettings.maxContextLength;
                    settingThinking.value = aiSettings.thinking;
                    settingRuleFile.value = aiSettings.ruleFilePath || '';
                } catch (e) {
                    console.error('加载设置失败:', e);
                }
            } else {
                // 首次加载，设置默认值到表单
                settingModelId.value = aiSettings.modelId;
                settingApiKey.value = aiSettings.apiKey;
                settingMaxTokens.value = aiSettings.maxTokens;
                settingTemperature.value = aiSettings.temperature;
                settingMaxContext.value = aiSettings.maxContextLength;
                settingThinking.value = aiSettings.thinking;
                settingRuleFile.value = aiSettings.ruleFilePath;
            }
        }

        // 初始化事件监听
        function initEvents() {
            // 发送按钮点击事件
            sendButton.addEventListener('click', sendMessage);
            
            // 输入框回车事件
            messageInput.addEventListener('keydown', (event) => {
                if (event.key === 'Enter' && !event.shiftKey) {
                    event.preventDefault();
                    sendMessage();
                }
            });
            
            // 状态按钮点击事件
            statusButton.addEventListener('click', toggleConnection);
            
            // 设置按钮点击事件
            settingsButton.addEventListener('click', showSettings);
            
            // 关闭设置弹窗
            closeSettings.addEventListener('click', hideSettings);
            cancelSettings.addEventListener('click', hideSettings);
            
            // 点击弹窗外部关闭
            settingsModal.addEventListener('click', (event) => {
                if (event.target === settingsModal) {
                    hideSettings();
                }
            });
            
            // 保存设置
            settingsForm.addEventListener('submit', (event) => {
                event.preventDefault();
                saveSettingsConfig();
            });
        }

        // 连接RPC服务器
        async function connectToRpc() {
            try {
                showLoading(true);
                addSystemMessage('正在连接RPC服务器...');
                
                // 创建RPC客户端
                rpcClient = new RpcClient();
                await rpcClient.connectRpc();
                
                // 创建Lua RPC实例
                luaRpc = new LuaRpc(rpcClient);
                
                // 创建VolcanoApi RPC实例
                volcanoApiRpc = new VolcanoApiRpc(luaRpc);
                
                isConnected = true;
                updateStatus('已连接');
                addSystemMessage('RPC服务器连接成功，可以开始聊天了');
                
                // 启用输入框和发送按钮
                messageInput.disabled = false;
                sendButton.disabled = false;
                
            } catch (error) {
                console.error('RPC连接失败:', error);
                addSystemMessage(`RPC连接失败: ${error.message || '未知错误'}`);
                updateStatus('连接失败');
            } finally {
                showLoading(false);
            }
        }

        // 发送消息给AI
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || !isConnected) {
                return;
            }
            
            try {
                // 清空输入框
                messageInput.value = '';
                
                // 添加用户消息
                addUserMessage(message);
                
                // 显示AI正在输入
                const typingMessage = addAiTypingMessage();
                
                // 创建Volcano API实例（如果尚未创建）
                if (!volcanoApi) {
                    const config = {
                        modelId: aiSettings.modelId,
                        apiKey: aiSettings.apiKey,
                        thinking: aiSettings.thinking,
                        maxTokens: aiSettings.maxTokens,
                        temperature: aiSettings.temperature,
                        maxContextLength: aiSettings.maxContextLength,
                        ruleFilePath: aiSettings.ruleFilePath
                    };
                    
                    addSystemMessage(`正在初始化AI模型: ${aiSettings.modelId}...`);
                    volcanoApi = await volcanoApiRpc.create(config);
                    isApiInitialized = true;
                    addSystemMessage(`AI模型初始化成功，现在可以开始对话了`);
                }
                
                // 发送消息并获取响应
                console.log('发送消息给火山引擎API:', message);
                const [response, error] = await volcanoApi.chat(message);
                
                if (error) {
                    // 处理错误
                    console.error('API调用失败:', error);
                    updateAiMessage(typingMessage, `API调用失败: ${error}`);
                } else if (response) {
                    // 处理成功响应
                    console.log('收到AI响应:', response);
                    updateAiMessage(typingMessage, response);
                } else {
                    // 无响应情况
                    updateAiMessage(typingMessage, '未收到AI响应');
                }
                
            } catch (error) {
                console.error('发送消息失败:', error);
                addSystemMessage(`消息发送失败: ${error.message || '未知错误'}`);
            }
        }

        // 添加用户消息
        function addUserMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message user';
            
            const contentElement = document.createElement('div');
            contentElement.textContent = message;
            
            const timestampElement = document.createElement('div');
            timestampElement.className = 'message-timestamp';
            timestampElement.textContent = getCurrentTimestamp();
            
            messageElement.appendChild(contentElement);
            messageElement.appendChild(timestampElement);
            chatMessages.appendChild(messageElement);
            
            // 滚动到底部
            scrollToBottom();
            
            return messageElement;
        }

        // 添加AI正在输入消息
        function addAiTypingMessage() {
            const messageElement = document.createElement('div');
            messageElement.className = 'message ai';
            messageElement.setAttribute('data-typing', 'true');
            
            const contentElement = document.createElement('div');
            contentElement.innerHTML = '<span class="loading-indicator"></span> AI正在思考...';
            
            const timestampElement = document.createElement('div');
            timestampElement.className = 'message-timestamp';
            timestampElement.textContent = getCurrentTimestamp();
            
            messageElement.appendChild(contentElement);
            messageElement.appendChild(timestampElement);
            chatMessages.appendChild(messageElement);
            
            // 滚动到底部
            scrollToBottom();
            
            return messageElement;
        }

        // 更新AI消息
        function updateAiMessage(messageElement, message) {
            messageElement.removeAttribute('data-typing');
            messageElement.querySelector('div:first-child').textContent = message;
            
            // 滚动到底部
            scrollToBottom();
        }

        // 添加系统消息
        function addSystemMessage(message) {
            const messageElement = document.createElement('div');
            messageElement.className = 'message system';
            messageElement.textContent = message;
            
            chatMessages.appendChild(messageElement);
            
            // 滚动到底部
            scrollToBottom();
            
            return messageElement;
        }

        // 更新状态
        function updateStatus(status) {
            if (status === '已连接') {
                statusButton.className = 'status-button status-connected';
                statusIcon.textContent = '✓';
                statusButton.title = '已连接，点击断开';
            } else if (status === '未连接') {
                statusButton.className = 'status-button status-disconnected';
                statusIcon.textContent = '⚠';
                statusButton.title = '未连接，点击连接';
            } else if (status === '连接失败') {
                statusButton.className = 'status-button status-disconnected';
                statusIcon.textContent = '✗';
                statusButton.title = '连接失败，点击重试';
            }
        }

        // 显示/隐藏加载指示器
        function showLoading(show) {
            if (show) {
                statusIcon.textContent = '⏳';
                statusButton.disabled = true;
            } else {
                updateStatus(isConnected ? '已连接' : '未连接');
                statusButton.disabled = false;
            }
        }

        // 切换连接状态
        async function toggleConnection() {
            if (isConnected) {
                // 断开连接
                await disconnectFromRpc();
            } else {
                // 连接RPC
                await connectToRpc();
            }
        }

        // 断开连接
        async function disconnectFromRpc() {
            try {
                showLoading(true);
                
                if (volcanoApi) {
                    await volcanoApi.close();
                    volcanoApi = null;
                    isApiInitialized = false;
                }
                
                if (luaRpc) {
                    luaRpc = null;
                }
                
                if (rpcClient) {
                    await rpcClient.disconnect();
                    rpcClient = null;
                }
                
                isConnected = false;
                updateStatus('未连接');
                addSystemMessage('RPC服务器已断开连接');
                
                // 禁用输入框和发送按钮
                messageInput.disabled = true;
                sendButton.disabled = true;
                
            } catch (error) {
                console.error('断开连接失败:', error);
                addSystemMessage(`断开连接失败: ${error.message || '未知错误'}`);
            } finally {
                showLoading(false);
            }
        }

        // 显示设置弹窗
        function showSettings() {
            // 加载当前设置到表单
            settingModelId.value = aiSettings.modelId;
            settingApiKey.value = aiSettings.apiKey;
            settingMaxTokens.value = aiSettings.maxTokens;
            settingTemperature.value = aiSettings.temperature;
            settingMaxContext.value = aiSettings.maxContextLength;
            settingThinking.value = aiSettings.thinking;
            
            settingsModal.style.display = 'flex';
        }

        // 隐藏设置弹窗
        function hideSettings() {
            settingsModal.style.display = 'none';
        }

        // 保存设置配置
        function saveSettingsConfig() {
            // 验证输入
            if (!settingModelId.value.trim()) {
                alert('请输入模型ID');
                settingModelId.focus();
                return;
            }
            
            if (!settingApiKey.value.trim()) {
                alert('请输入API密钥');
                settingApiKey.focus();
                return;
            }
            
            if (!settingMaxTokens.value || settingMaxTokens.value < 1) {
                alert('请输入有效的最大Token数');
                settingMaxTokens.focus();
                return;
            }
            
            if (!settingTemperature.value || settingTemperature.value < 0 || settingTemperature.value > 2) {
                alert('请输入有效的温度值（0-2）');
                settingTemperature.focus();
                return;
            }
            
            if (!settingMaxContext.value || settingMaxContext.value < 1) {
                alert('请输入有效的最大上下文长度');
                settingMaxContext.focus();
                return;
            }
            
            // 保存设置
            aiSettings = {
                modelId: settingModelId.value.trim(),
                apiKey: settingApiKey.value.trim(),
                maxTokens: parseInt(settingMaxTokens.value),
                temperature: parseFloat(settingTemperature.value),
                maxContextLength: parseInt(settingMaxContext.value),
                thinking: settingThinking.value,
                ruleFilePath: settingRuleFile.value.trim()
            };
            
            // 保存到localStorage
            localStorage.setItem('aiSettings', JSON.stringify(aiSettings));
            
            // 如果已经初始化了API，需要重新初始化
            if (isApiInitialized) {
                addSystemMessage('设置已保存，需要重新连接以应用新设置');
                // 断开连接，让用户手动重新连接
                if (isConnected) {
                    disconnectFromRpc();
                }
            } else {
                addSystemMessage('设置已保存');
            }
            
            // 关闭弹窗
            hideSettings();
        }

        // 滚动到底部
        function scrollToBottom() {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        // 获取当前时间戳
        function getCurrentTimestamp() {
            const now = new Date();
            const hours = now.getHours().toString().padStart(2, '0');
            const minutes = now.getMinutes().toString().padStart(2, '0');
            const seconds = now.getSeconds().toString().padStart(2, '0');
            return `${hours}:${minutes}:${seconds}`;
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadSettings();
            initEvents();
        });
    </script>
</body>
</html>